package com.itheima.exerciseTest.method50_59.method50;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Properties;
import java.util.Set;

public class Demo2 {
    public static void main(String[] args) throws IOException, ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException, NoSuchFieldException {
        // 获取配置文件信息放到双列集合中
        ClassLoader systemClassLoader = ClassLoader.getSystemClassLoader();
        BufferedReader br = new BufferedReader(new InputStreamReader(systemClassLoader.getResourceAsStream("com\\itheima\\exerciseTest\\method50_59\\method50\\student.properties"), "gbk"));
        Properties prop = new Properties();
        prop.load(br);
        br.close();

        Class className = Class.forName(prop.getProperty("className"));
        Constructor constructor = className.getConstructor();
        Object o = constructor.newInstance();

        Set<String> fieldNames = prop.stringPropertyNames();
        for (String fieldName : fieldNames) {
            if(!"className".equals(fieldName)){
                Field field = className.getDeclaredField(fieldName);
                Class type = field.getType();
                String methodName = "set" + fieldName.substring(0,1).toUpperCase() + fieldName.substring(1);
                Method method = className.getMethod(methodName, type);
                if(type == int.class){
                    int value = Integer.parseInt(prop.getProperty(fieldName));
                    method.invoke(o,value);
                }else{
                    String value = prop.getProperty(fieldName);
                    method.invoke(o,value);
                }
            }
        }
        System.out.println(o);
    }
}
